package com.SinaMicrobloggingAPI.Util;

import java.net.URLEncoder;
import java.util.Dictionary;
import java.util.Hashtable;

public class HttpUtility {

	public static final String UNRESERVED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.*";

	public static String urlEncodeWithLowerCase(String value) {
		StringBuilder result = new StringBuilder();
		String encodeStr = value.trim();
		int length = encodeStr.length();
		char symbol;
		String formatStr = "";
		for (int i = 0; i < length; i++) {
			symbol = encodeStr.charAt(i);
			if (UNRESERVED_CHARS.indexOf(symbol) != -1) {
				result.append(symbol);
			} else {
				formatStr = Integer.toHexString(symbol);
				result.append("%");
				result.append(formatStr);
			}
		}
		return result.toString();
	}

	public static String urlEncodeWithUpperCase(String value) {
		String encodeUrl = "";
		try {
			encodeUrl = URLEncoder.encode(value.trim(), "UTF-8");
		} catch (Exception ex) {

		}
		return encodeUrl;
	}

	public static Dictionary<String, String> parseQueryString(String queryString) {
		if (queryString == "" || !queryString.contains("&"))
			return null;

		String[] nameValues = queryString.split("&");
		String[] result = null;
		if (nameValues != null) {
			Dictionary<String, String> nameValueCollection = new Hashtable<String, String>();
			for (int i = 0; i < nameValues.length; i++) {
				result = nameValues[i].split("=");
				nameValueCollection.put(result[0], result[1]);
			}
			return nameValueCollection;
		}
		return null;
	}
}
